import { defineStore } from 'pinia';
import {
  findByOpenId,
  loginMiniApp,
  getUserBindMechanism,
} from '@/api/methods/auth';
import { getPlatformInfo, unLimitGenerateCode } from "@/api/methods/system";
import { clearToken, setToken } from '@/hooks/auth';
import storage from '@/utils/storage';

const useStore = defineStore('user', {
  // arrow function recommended for full type inference
  state: () => ({
    // all these properties will have their type inferred automatically
    userInfo: null,
    sysInfo: null,
    isFirst: true,
    shareQrCode: '',
    bindMechanismList: [],
  }),
  getters: {
    isLogin: (state) => {
      return uni.getStorageSync('token') !== '' || state.userInfo !== null;
    },
    permissionList: (state) => {
      return state.userInfo?.permissionList || null;
    },
    isBusiness: (state) => {
      return state.userInfo?.isSysUser === 1 || null;
    },
    noHaveBusiness: (state) => {
      return !state.userInfo?.mechanismId;
    },
  },
  actions: {
    async registerUser(e, loginCode) {
      try {
        console.log(e);
        const { encryptedData, errMsg, iv } = e.detail || e;
        if (loginCode) {
          uni.checkSession({
            fail: async () => {
              const { code } = await uni.login();
              loginCode = code;
            },
          });
        } else {
          const { code } = await uni.login();
          loginCode = code;
        }

        if (errMsg !== 'getPhoneNumber:ok')
          return uni.showToast({ title: '用户取消授权', icon: 'none' });
        const res = await loginMiniApp({
          code: loginCode,
          encrypdata: encryptedData,
          ivdata: iv,
        });
        this.setUserInfo(res);
        return !res.token;
      } catch (_e) {
        console.log(_e);
        return true;
      }
    },
    async getSystemInfo() {
      const res = await getPlatformInfo();
      this.sysInfo = res.data;
    },
    setUserInfo(data) {
      storage.set("PERMISSIONS", data.permissionList || "");
      storage.set("MID", data.mechanismId || "");
      setToken(data.token);
      this.userInfo = data;
      if (data?.mechanismId) {
        const sendData = {
          path: 'pages/bindCanteen/bindCanteenInfo',
          scene: data.mechanismId,
        };
        unLimitGenerateCode(sendData).then((qrData) => {
          this.shareQrCode = `data:image/png;base64,${qrData || ''}`;
        });
      }
    },
    async autoLogin() {
      try {
        const { code } = await uni.login();
        const res = await findByOpenId({ code });
        if (res.token) {
          this.setUserInfo(res);
          this.getBindMechanism();
        } else {
          clearToken();
        }
        return true;
      } catch (_e) {
        return true;
      } finally {
        this.isFirst = false;
      }
    },
    async getBindMechanism() {
      const list = await getUserBindMechanism();
      this.bindMechanismList = list || [];
    },
  },
});

export default useStore;
